package com.easysoft.commons.utils;

import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

public class FTPUtils {
    private FTPClient ftp;

    public FTPUtils(String address, int port, String userName, String passWord) throws IOException {
        ftp = new FTPClient();
        ftp.connect(address, port);
        ftp.login(userName, passWord);
    }

    public boolean upload(String path, File file) throws IOException {
        int reply = ftp.getReplyCode();
        if (FTPReply.isPositiveCompletion(reply)) {
            ftp.changeWorkingDirectory(path);
            return ftp.storeFile(file.getName(), new FileInputStream(file));
        }
        return false;
    }

    public void dispose() throws IOException {
        ftp.logout();
        ftp.disconnect();
    }

    public static void main(String[] args){
        try {
            FTPUtils ftpUtils = new FTPUtils("192.168.1.110",21,"kin","kin");
            ftpUtils.upload("/",new File("C:\\Users\\Administrator\\Desktop\\1.txt"));
            ftpUtils.dispose();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

//public class FTPUtils {
//    private static boolean isInit;
//    private static String address;
//    private static int port;
//    private static String userName;
//    private static String passWord;
//
//    public static void init(String address, int port, String userName, String passWord) {
//        FTPUtils.address = address;
//        FTPUtils.port = port;
//        FTPUtils.userName = userName;
//        FTPUtils.passWord = passWord;
//        FTPUtils.isInit = true;
//    }
//
//    public static boolean uploadFile(String s, String path, File file) {
//        Boolean result = false;
//        if (isInit) {
//            FTPClient ftp = new FTPClient();
//            try {
//                ftp.connect(address, port);
//                ftp.login(userName, passWord);
//                int reply = ftp.getReplyCode();
//                if (FTPReply.isPositiveCompletion(reply)) {
//                    ftp.changeWorkingDirectory(path);
//                    ftp.storeFile(file.getName(), new FileInputStream(file));
//                    ftp.logout();
//                    result = true;
//                }
//            } catch (IOException e) {
//                result = false;
//            } finally {
//                if (ftp.isConnected()) {
//                    try {
//                        ftp.disconnect();
//                    } catch (IOException e) {
//                        e.printStackTrace();
//                    }
//                }
//            }
//        } else {
//            System.out.print("FTPUtils未初始化");
//        }
//        return result;
//    }
//}